package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

/**
 * @Author Mr.Wen
 * @Version 1.0
 */
@Component
@Slf4j
public class CacheClient {
    private final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set(String key, Object value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

    public void setWithLogicExpire(String key, Object value, Long time, TimeUnit unit) {
//        设置逻辑过期
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));

    }

    /**
     * redis空值解决缓存穿透
     *
     * @param keyPrefix
     * @param id
     * @param type
     * @param dbFallback
     * @param time
     * @param unit
     * @param <R>
     * @param <ID>
     * @return
     */
    public <R, ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback
            , Long time, TimeUnit unit) {
        //从redis查询商铺缓存
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
//    判断是否存在
        if (StrUtil.isNotBlank(json)) {
            return JSONUtil.toBean(json, type);
        }
//        判断命中的是否为空值
        if (json != null) {
            return null;
        }
//    不存在，根据id查询数据库
        R r = dbFallback.apply(id);
//    数据库不存在，返回错误
        if (r == null) {
//            先设置为空字符串
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
//    数据库存在，写入redis，返回结果
        this.set(key, r, time, unit);
        return r;
    }

    /**
     * 模拟逻辑日期
     *
     * @param id
     * @return
     */
    public <R, ID> R queryWithLogicExpire(String prefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit) {
        //从redis查询商铺缓存

        String key = prefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
//      如果未命中说明此刻缓存正在被使用，直接返回null
        if (StrUtil.isBlank(json)) {
            return null;
        }
//        命中，就先把Json反序列化为对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
//        判断expire属性是否过期，如果未过期就直接返回
        if (expireTime.isAfter(LocalDateTime.now())) {
            return r;
        }
//        如果已过期，就重建缓存
//        要先获取互斥锁，判断是否获取锁成功
        String lockKey = LOCK_SHOP_KEY + id;
        Boolean shopLock = tryLock(lockKey);
//        如果成功，就开启新线程实现缓存重建
        if (shopLock) {
            CACHE_REBUILDER_EXECUTOR.submit(() -> {
                try {
//                    查询数据库
                    R r1 = dbFallback.apply(id);
//                    写入redis
                    this.setWithLogicExpire(key, r1, time, unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
//                释放锁
                    unLock(lockKey);
                }
            });
        }
//         返回店铺信息
        return r;
    }

    /*创建一个线程池*/
    private static final ExecutorService CACHE_REBUILDER_EXECUTOR = Executors.newFixedThreadPool(10);

    /**
     * 加锁
     *
     * @param key
     */
    public Boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 20, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 释放锁
     *
     * @param key the key
     */
    public void unLock(String key) {
        stringRedisTemplate.delete(key);
    }
}
